package com.cdtu.store.filter;

import com.cdtu.store.auth.utils.JwtUtils;
import com.cdtu.store.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author dongyuhao
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private JwtProperties prop;

    public static final String[] FILTER_URL= {"/api/auth","/api/search","/api/user/register","/api/user/check","/api/user/code","/api/item","/api/oss","/api/renren-fast","/api/cart"};
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();
        //跳过不需要验证的路径
        System.out.println(url);
        for (String path : FILTER_URL) {
            if(url.startsWith(path)){
                System.out.println("跳过验证");
                return chain.filter(exchange);
            }
        }
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        String token = null;
        if (cookies.getFirst(this.prop.getCookieName()) != null) {
            token = cookies.getFirst(this.prop.getCookieName()).getValue();
        }
        if (token != null) {
            try {
                JwtUtils.getInfoFromToken(token, this.prop.getPublicKey());
            } catch (Exception e) {
                return error(response,"认证失败");
            }
        }else{
            return error(response,"未认证");
        }
        return chain.filter(exchange);
    }

    private Mono<Void> error(ServerHttpResponse response, String json) {
        //返回错误
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        DataBuffer buffer = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return -200;
    }
}
